package com.platform.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.platform.annotation.IgnoreAuth;
import com.platform.constant.ApiConstant;
import com.platform.entity.MlsUserEntity2;
import com.platform.entity.UserVo;
import com.platform.service.ApiUserService;
import com.platform.service.MlsUserSer;
import com.platform.service.TokenService;
import com.platform.util.ApiBaseAction;
import com.platform.util.ApiUserUtils;
import com.platform.util.wechat.MessageType;
import com.platform.util.wechat.MessageUtil;
import com.platform.utils.Base64;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * API公众号登录授权
 */
@Api(tags = "登录授权接口")
@RestController
@RequestMapping("/api/auth")
public class ApiAuthController extends ApiBaseAction {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${weixin.mp.token}")
    private String mpToken;
    @Value("${weixin.mp.message}")
    private String mpMessage;

    @Value("classpath:data/weixinMenu.json")
    private Resource menuRes;

    @Value("${weixin.mp.env}")
    private String env;

    @Autowired
    private ApiUserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
	private MlsUserSer mlsUserSer;


    /**
     * 登录公众号
     * 拦截器token控制是否已登录，没有登录则调用该方法
     *
     * 1. 普通关注用户，通过首页进入
     * a. 首页进入时，通过网页授权获取用户基本信息
     *
     *
     * 2. 通过推荐人分享链接进入==》分享url,带上推荐人id
     *
     *
     * 3. 通过推荐人二维码扫码进入==》分享url,带上推荐人id
     */
    @IgnoreAuth
    @ApiOperation(value = "健国e商-登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "promoterId", value = "推荐人Id", dataType = "Integer", paramType = "query", required = false)
    })
    @GetMapping("loginMp")
    public void loginMp(@RequestParam(value="promoterId", required = false) Integer promoterId){
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        String path = request.getContextPath();
        String REDIRECT_URI = URLEncoder.encode(scheme + "://" + serverName + path + "/api/auth/loginMpCallBack");

        // 获取code
        String codeUrl = ApiUserUtils.getCode(REDIRECT_URI, "snsapi_userinfo", promoterId);

        try {
            response.sendRedirect(codeUrl);//必须重定向，否则不能成功
        } catch (IOException e) {
            logger.error("重定向失败", e);
        }
    }

    @IgnoreAuth
    @ApiOperation(value = "健国e商-登录回调")
    @GetMapping("loginMpCallBack")
    public Object loginMpCallBack(HttpServletRequest request){
        UserVo userVo = null;
        Long promoterId = 0L;
        if(!"local".equals(env)){
            String code = request.getParameter("code");
            logger.info("》》》code:{}", code);

            String state = request.getParameter("state");
            if(StringUtils.isNotEmpty(state) && !"null".equals(state)){
                try{
                    promoterId = Long.parseLong(state);
                }catch (Exception e){
                    logger.error("state转换成promoterId失败，state:"+state, e);
                }
            }

            // 通过code换取网页授权access_token
            String accessTokenUrl = ApiUserUtils.getWebAccess(code);
            String res = restTemplate.getForObject(accessTokenUrl, String.class);
            logger.info("accessTokenUrl res：{}", res);
            JSONObject sessionData = JSON.parseObject(res);
            String access_token = sessionData.getString("access_token");
            String openid = sessionData.getString("openid");

            userVo = userService.queryByOpenId(openid);
            if(userVo == null){
                // 获取用户信息
                String userUrl = ApiUserUtils.getUserMessage(access_token, openid);
                res = restTemplate.getForObject(userUrl, String.class);
                try {
                    res = new String(res.getBytes("ISO-8859-1"), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    logger.error("用户信息转换异常", e);
                }
                logger.info("userUrl res：{}", res);
                JSONObject userData = JSON.parseObject(res);
                logger.info(JSONObject.toJSONString(userData));

                userVo = new UserVo();
                userVo.setWeixin_openid(openid);
                userVo.setNickname(userData.getString("nickname"));
                userVo.setUsername(Base64.encode(userVo.getNickname()));
                userVo.setPassword(openid);
                userVo.setRegister_time(new Date());
                userVo.setRegister_ip(this.getClientIp());
                userVo.setLast_login_ip(userVo.getRegister_ip());
                userVo.setLast_login_time(userVo.getRegister_time());
                userVo.setWeixin_openid(openid);
                userVo.setAvatar(userData.getString("headimgurl"));
                userVo.setGender(userData.getInteger("sex")); // //性别 0：未知、1：男、2：女
                userVo.setUser_level_id(1);// 默认为访客
                userVo.setProvince(userData.getString("province"));
                userVo.setCity(userData.getString("city"));
                userVo.setCountry(userData.getString("country"));
                JSONArray privilege = userData.getJSONArray("privilege");
                if(privilege != null && privilege.size() > 0){
                    userVo.setPrivilege(privilege.toJSONString());
                }
                userVo.setUnionid(userData.getString("unionid"));

                //判断是否是推广用户登录
                if(promoterId != 0){
                    userVo.setPromoterId(promoterId);
                    UserVo promoterUser = userService.queryObject(new Long(promoterId));
                    if(promoterUser != null){
                        userVo.setPromoterName(promoterUser.getUsername());
                    }
                }

                userService.save(userVo);

                // 分销用户
                MlsUserEntity2 fmlsUser= new MlsUserEntity2();
                if(promoterId != 0) {
                    MlsUserEntity2 mlsuser = this.mlsUserSer.getEntityMapper().findByUserId(new Long(promoterId));
                    // 设置上级
                    fmlsUser.setFid(mlsuser.getMlsUserId());
                }
                fmlsUser.setUserId(userVo.getUserId());
                fmlsUser.setNickname(userVo.getNickname());
                fmlsUser.setLoginPassword(userVo.getPassword());
                fmlsUser.setMerchantId(ApiConstant.DEFAULT_MERCHANT_ID);
                fmlsUser.setDeviceId(openid);
                this.mlsUserSer.insUser(fmlsUser);
            }
        }else{
            userVo = userService.queryObject(111L);
        }
        // Map<String, Object> tokenMap = tokenService.createToken(userVo.getUserId());

        Map<String, Object> resultObj = new HashMap<String, Object>();
        resultObj.put("userVo",userVo);

        //resultObj.put("tokenMap",tokenMap);
        return toResponsSuccess(resultObj);
    }
}
